#include "Grid.h"

Grid::Grid(DxManager * dxmanager)
{
	PosX = GRID_PX;//32;
	PosY = GRID_PY;//3;

	SizeX = GRID_SX;//10;
	SizeY = GRID_SY;//18;

	dxm = dxmanager;

	Init();
}

void Grid::Init()
{
	G_Space = new T_Block*[SizeY];
	int tx = 0;

	for(int y = 0; y < SizeY; y++)
	{
		G_Space[y] = new T_Block[SizeX];
		for(int x = 0; x < SizeX; x++)
		{
			G_Space[y][x].Init(dxm);
		}
	}
}

Grid::~Grid()
{
	for(int y = 0; y < SizeY; y++)
	{
		delete [] G_Space[y];
	}

	delete [] G_Space;
}

void Grid::DrawOutline()
{
	//Draw DirectX
}

void Grid::DrawGrid()
{
	for(int y = 0; y < SizeY; y++)
	{
		for(int x = 0; x < SizeX; x++)
		{
			if(G_Space[y][x].GetOccupation())
			{
				//Change Color 
				//Move Position to draw
				//Draw each indivual T_Block
				G_Space[y][x].Draw(dxm, x+PosX, y+PosY,G_Space[y][x].getColor());
			}
		}
	}

}

void Grid::Clr_Grid()
{
	COORD c = {PosX,0};
	for(int y = 0; y < SizeY; y++)
	{
		c.Y = PosY + y;
		//Clear T_Block
	}
}

bool Grid::StopTetri(int tx,int ty, Tetrimino T)
{
	for(int x = 0; x < P_NUM; x++)
	{
		int nx = tx + T.GetPoint(x).X;
		int ny = ty + T.GetPoint(x).Y;

		if(nx <= ((SizeX) - 1) && nx >= 0 && ny <= ((SizeY)-1) && ny > 0)
		{
			G_Space[ty+T.GetPoint(x).Y][tx+T.GetPoint(x).X].BlockColor(T.getColor());
			G_Space[ty+T.GetPoint(x).Y][tx+T.GetPoint(x).X].SetTrue();
		}
		else
			return false;
	}
	return true;
}

int Grid::FullRow()
{
	int y = 0;
	bool rowFull = true;
	for(y = 0; y < GRID_SY; y++)
	{
		rowFull = true;
		for(int x = 0; x < GRID_SX; x++)
		{
			if(!G_Space[y][x].GetOccupation())
				rowFull = false;

			if(!rowFull)
				break;
		}

		if(rowFull)
			break;
	}

	if(rowFull && y > 0)
		return y;
	else
		return 0;
}

void Grid::ClearRow(int row)
{
	for(int y = row; y >= 0; y--)
	{
		for(int x = 0; x < GRID_SX; x++)
		{
			if(y == 0)
			{
				G_Space[y][x].Init(dxm);
			}
			else
			{
				if(G_Space[y-1][x].GetOccupation())
					G_Space[y][x].SetTrue();
				else
					G_Space[y][x].SetFalse();

				G_Space[y][x].BlockColor(G_Space[y-1][x].getColor());
			}
		}
	}
}

bool Grid::ClearBlock(int px, int py)
{
	for(int x = 0; x < GRID_SX; x++)
	{
		for(int y = 0; y < GRID_SY; y++)
		{
			if(G_Space[y][x].getRect().top < py && G_Space[y][x].getRect().bottom > py)
			{
				if(G_Space[y][x].getRect().left < px && G_Space[y][x].getRect().right > px)
				{
					if(G_Space[y][x].GetOccupation())
					{
						G_Space[y][x].SetFalse();
						return true;
					}
				}
			}
		}
	}
	return false;
}